﻿using System.Security.Cryptography;
using System.Text;

/********************************************
* 公司名称：snail information
* 创 建 人：cfhknight
* 创建日期：2025/9/29 13:32:39
* 说    明：string extensions
* 版    本：V0.0.0.1
********************************************/
namespace SnailInfo.ConvertExtension
{
    public static class StringExtension
    {
        public static string Left(this string value, int iLength)
        {
            if (iLength > value.Length) {
                return value;
            }
            return value.Substring(0, iLength);
        }

        public static string Right(this string value, int iLength)
        {
            if (iLength > value.Length) {
                return value;
            }
            return value.Substring(value.Length - iLength, iLength);
        }

        public static string ToHashString(this string value)
        {
            if (string.IsNullOrWhiteSpace(value)) {
                return string.Empty;
            }
            using (MD5 md5 = MD5.Create()) {
                byte[] array = md5.ComputeHash(Encoding.UTF8.GetBytes(value));
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < array.Length; i++) {
                    stringBuilder.Append(array[i].ToString("x2"));
                }

                return stringBuilder.ToString();
            }
        }

        public static string ToSHA256String(this string value)
        {
            using (var sha256 = SHA256.Create()) { 
                var array = sha256.ComputeHash(Encoding.UTF8.GetBytes(value));
#if NET
                Console.WriteLine("Is Net");
               return Convert.ToHexString(array);
#else
                Console.WriteLine("IsNetFramwork");
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < array.Length; i++) {
                    stringBuilder.Append(array[i].ToString("x2"));
                }

                return stringBuilder.ToString();
#endif
            }
        }

        public static string ToHashString(this string value, string salt)
        {
            if (string.IsNullOrWhiteSpace(value)) {
                return string.Empty;
            }
            using (MD5 md5 = MD5.Create()) {
                byte[] array = md5.ComputeHash(Encoding.UTF8.GetBytes($"{value}{salt}"));
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < array.Length; i++) {
                    stringBuilder.Append(array[i].ToString("x2"));
                }

                string encryptString = stringBuilder.ToString();
                return encryptString;
            }
        }
    }
}
